home *** CD-ROM | disk | FTP | other *** search
- Path: ip-pdx09-31.teleport.com!user
- From: peteski@teleport.com (Peter Miller)
- Newsgroups: comp.lang.c
- Subject: Re: Global variables in a multiple-sourcefile application
- Date: Thu, 21 Mar 1996 22:20:58 -0700
- Organization: Teleport - Portland's Public Access (503) 220-1016
- Message-ID: <peteski-2103962220580001@ip-pdx09-31.teleport.com>
- References: <827255412.29892.0@fersys.demon.co.uk>
- NNTP-Posting-Host: ip-pdx09-31.teleport.com
-
- In article <827255412.29892.0@fersys.demon.co.uk>, mlb@fersys.demon.co.uk wrote:
-
- > I have two questions about the use of global variables in a
- > multiple-sourcefile application:
- >
- > 1) If I have a global variable x that is used in both source files of
- > an application, but I don't need it initialised in its definition,
- > I would generally put "int x;" in one and "extern int x;" in the other.
- >
- > However, is there anything unsafe about putting a declaration in a header
- > file included by both files, without a definition in either file, or
- > do I really need a definition in one of the files?
- >
- > i.e. is this OK?:
- > Mark Bergman Email: mlb@fersys.co.uk
- > Ferranti Syseca Ltd. Tel: 0161-946 7178
- > Wythenshawe, Manchester, UK Fax: 0161-946 7001
-
-
- 1) I would expect that the modules would compile but would not link together.
- No, you are going to have to define the variable in one file, and declare
- it extern in the other file, otherwise the linker will not create an
- executable.
-
- so, typically, in the main module you would define the variable:
- int x;
- and in the other module, declare it:
- extern int x;
-
- 2) It is very dangerous to have data with the same name declared
- differently between source files. If the actual variable is smaller than
- the external declaration, then use of that variable externally will likely
- cause memory reads and writes out of bounds. If the actual variable is of
- a larger size than the external declaration, then unexpected values are
- likely to result. In either case, doom and aggravation are the most
- likely result.
-
- Sincerely,
-
- Peter Miller
-